package cn.tedu.thread;/**
 * @Author 金帮嘉诚 @Date 2021-06-25 星期五 8:47
 */
/*本类用于测试ReentrantReadWriteLock读写锁 和ExecutorService线程池 的使用*/

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 知识点
 */
public class TestThread1 {
    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        //线程池只是一种创建线程的方式
        //用线程池了也会有多线程数据冲突问题，因此还是要用锁
        ExecutorService es1 = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            es1.execute(myThread1);
        }
    }
}

class MyThread1 implements Runnable {
    int add = 100;
    Object object = new Object();
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @Override
    public void run() {
        while (true) {
            //在操作共享资源之前上锁
            readWriteLock.writeLock().lock();
            try {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (add > 0) {
                    System.out.println(add--);
                }
                if (add <= 0) break;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                readWriteLock.writeLock().unlock();
            }
        }
    }
}
